<template>
  <div class="form-layer">
    <div class="form-wrapper">
      <a-form ref="form" :model="formData" layout="inline">
        <a-form-item label="模块名称" name="moduleName" class="default-margin">
          <a-input v-model:value="formData.moduleName" />
        </a-form-item>
        <a-form-item label="事件类型" name="eventType" class="default-margin">
          <a-input v-model:value="formData.eventType" />
        </a-form-item>
        <a-form-item label="时间范围" class="default-margin">
          <a-range-picker
            :show-time="{ format: 'HH:mm' }"
            format="YYYY-MM-DD HH:mm:ss"
            :placeholder="['Start Time', 'End Time']"
            @ok="onRangeOk"
          />
        </a-form-item>
        <a-form-item class="default-margin">
          <a-button type="primary" @click="handleQuery">查询</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
  <div class="table-layer">
    <div class="event-table">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="false"
        :row-key="(record) => record.eventId"
        :row-selection="rowSelection"
        :scroll="{ y: '700px' }"
        size="small"
        tableLayout="fixed"
        bordered
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'attribute'">
            <div class="attr" @click="record.show = !record.show">
              <template v-if="record.show === true">
                <pre>{{ showAttribute(record.attribute) }}</pre>
              </template>
              <template v-else>
                {{ record.attribute }}
              </template>
            </div>
          </template>
          <template v-if="column.key === 'operation'">
            <a style="color: red" @click="handleDelete(record)">删除</a>
          </template>
        </template>
      </a-table>
    </div>
  </div>
  <div class="pagination-layer">
    <div class="dropdown-wrapper">
      <a-dropdown v-if="showBatchOperation">
        <template #overlay>
          <a-menu @click="handleMenuClick">
            <a-menu-item key="1">
              <DeleteOutlined />
              删除
            </a-menu-item>
          </a-menu>
        </template>
        <a-button>
          批量操作
          <DownOutlined />
        </a-button>
      </a-dropdown>
    </div>
    <div class="pagination-wrapper">
      <a-pagination
        :current="currentPage"
        :page-size="pageSize"
        :total="total"
        :show-total="(total) => `总数 ${total}`"
        responsive
        show-size-changer
        show-less-items
        @change="onPageChange"
        @show-size-change="onShowSizeChange"
      />
    </div>
  </div>
</template>

<script>
  import {
    Button,
    Input,
    Pagination,
    Table,
    message,
    Form,
    FormItem,
    RangePicker,
    Dropdown,
    Menu,
    MenuItem,
  } from 'ant-design-vue'
  import { getEventList, deleteEvent, batchDeleteEvent } from '/@/api/module/event'
  import { useModuleStoreWithOut } from '/@/store/modules/module'
  import { DeleteOutlined, DownOutlined } from '@ant-design/icons-vue'

  export default {
    components: {
      'a-input': Input,
      'a-table': Table,
      'a-form': Form,
      'a-form-item': FormItem,
      'a-range-picker': RangePicker,
      'a-button': Button,
      'a-pagination': Pagination,
      'a-dropdown': Dropdown,
      'a-menu': Menu,
      'a-menu-item': MenuItem,
      DeleteOutlined,
      DownOutlined,
    },
    data() {
      return {
        store: useModuleStoreWithOut(),
        mouseOverRecord: null,
        rowSelection: {
          selectedRowKeys: [],
          onChange: this.onSelectChange,
        },
        formData: {
          moduleName: '',
          eventType: '',
          startTime: '',
          endTime: '',
        },
        currentPage: 1,
        pageSize: 10,
        total: 10,
        loading: false,
        showJson: false,
        tableData: [],
        columns: [
          {
            title: 'Event ID',
            key: 'eventId',
            dataIndex: 'eventId',
            align: 'center',
            width: 100,
          },
          {
            title: 'Module ID',
            key: 'moduleId',
            dataIndex: 'moduleId',
            align: 'center',
            width: 100,
          },
          {
            title: 'Module Name',
            key: 'moduleName',
            dataIndex: 'moduleName',
            align: 'center',
            width: 200,
          },
          {
            title: 'Event Type',
            key: 'eventType',
            dataIndex: 'eventType',
            align: 'center',
            width: 200,
          },
          {
            title: 'Attribute',
            key: 'attribute',
            dataIndex: 'attribute',
            ellipsis: true,
          },
          {
            title: 'Create Time',
            key: 'createTime',
            dataIndex: 'createTime',
            align: 'center',
            width: 200,
          },
          {
            title: 'Operation',
            key: 'operation',
            dataIndex: 'operation',
            align: 'center',
            fixed: 'right',
            width: 120,
          },
        ],
      }
    },
    computed: {
      showBatchOperation() {
        return this.rowSelection.selectedRowKeys.length > 0
      },
    },
    mounted() {
      this.updateTableData()
    },
    methods: {
      formateDate(date) {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hour = String(date.getHours()).padStart(2, '0')
        const minute = String(date.getMinutes()).padStart(2, '0')
        const second = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`
      },
      onRangeOk(value) {
        this.formData.startTime = value[0].format('YYYY-MM-DD HH:mm:ss')
        this.formData.endTime = value[1].format('YYYY-MM-DD HH:mm:ss')
      },
      handleQuery() {
        this.updateTableData()
      },
      async onShowSizeChange(current, size) {
        this.pageSize = size
        this.currentPage = 1
        this.updateTableData()
      },
      onPageChange(page) {
        this.currentPage = page
        this.updateTableData()
      },
      updateTableData() {
        this.loading = true
        this.rowSelection.selectedRowKeys = []
        getEventList({
          rootModuleId: this.store.getRoot.id,
          moduleName: this.formData.moduleName,
          eventType: this.formData.eventType,
          startTime: this.formData.startTime,
          endTime: this.formData.endTime,
          pageSize: this.pageSize,
          pageIndex: this.currentPage,
        })
          .then((data) => {
            this.tableData = data.events
            this.total = data.totalSize
            this.loading = false
          })
          .catch((e) => {
            message.error('get event list failed')
            console.error('get event list failed', e)
            this.loading = false
          })
      },
      showAttribute(data) {
        let jsonObj = JSON.parse(data)
        if (jsonObj) {
          return JSON.stringify(jsonObj, null, 2)
        } else {
          return data
        }
      },
      handleDelete(record) {
        console.log('delete:', record)
        deleteEvent({
          eventId: record.eventId,
        })
          .then(() => {
            this.updateTableData()
          })
          .catch((e) => {
            message.error('delete record failed', e)
          })
      },
      onSelectChange(selectedRowKeys) {
        this.rowSelection.selectedRowKeys = selectedRowKeys
      },
      handleBatchDelete() {
        batchDeleteEvent({
          events: this.rowSelection.selectedRowKeys,
        })
          .then(() => {
            message.success('batch delete success')
            this.updateTableData()
          })
          .catch((e) => {
            console.error('batch delete failed', e)
            message.error('batch delete failed')
          })
      },
      handleMenuClick(e) {
        console.log('e:', eval)
        if (e.key === '1') {
          this.handleBatchDelete()
        }
      },
    },
  }
</script>

<style scoped>
  .event-table {
    width: 100%;
    margin-left: 10px;
    margin-right: 10px;
  }
  .event-table .attr {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .form-layer {
    display: flex;
    justify-content: center;
  }
  .form-wrapper {
    margin-left: 10px;
    margin-right: 10px;
    width: 100%;
    border-width: 1px;
    border-style: solid;
    border-color: #f0f0f0;
    padding-top: 10px;
    padding-bottom: 10px;
  }
  .default-margin {
    margin-left: 10px;
  }
  .table-layer {
    display: flex;
    justify-content: center;
    margin-top: 10px;
  }
  .pagination-layer {
    margin-top: 8px;
    display: flex;
    justify-content: space-between;
  }
  .pagination-wrapper {
    margin-left: auto;
    margin-right: 10px;
  }
  .dropdown-wrapper {
    margin-left: 10px;
    margin-right: auto;
  }
</style>
